package cn.com.greatwall.flowable.service.mapstruct;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.HistoryService;
import org.flowable.engine.IdentityService;
import org.flowable.engine.task.Comment;
import org.flowable.idm.api.User;
import org.flowable.task.api.TaskInfo;
import org.springframework.stereotype.Component;

import cn.com.greatwall.common.base.BaseMapper;
import cn.com.greatwall.flowable.common.CommentTypeEnum;
import cn.com.greatwall.flowable.service.dto.CommentDto;
import lombok.RequiredArgsConstructor;

/**
 * @Author herw
 * @Time 2020-11-24 15:09:27
 * @Version 1.0
 * @Description: TODO(用一句话描述该文件做什么)
 */
@Component
@RequiredArgsConstructor
public class CommentMapper implements  BaseMapper<CommentDto, Comment> {
    private final IdentityService identityService;
    private final HistoryService historyService;
    @Override
    public Comment toEntity(CommentDto dto) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public CommentDto toDto(Comment entity) {
        CommentDto dto = new CommentDto();
        dto.setId(entity.getId());
        dto.setUserId(entity.getUserId());
        dto.setUserName(getUserName(entity.getUserId()));
        dto.setType(entity.getType());
        dto.setTypeDesc(CommentTypeEnum.getEnumMsgByType(entity.getType()));
        dto.setTime(entity.getTime());
        dto.setProcessInstanceId(entity.getProcessInstanceId());
        dto.setTaskId(entity.getTaskId());
        TaskInfo task = historyService.createHistoricTaskInstanceQuery().taskId(entity.getTaskId()).singleResult();
        dto.setTaskName(task.getName());
        dto.setFullMessage(entity.getFullMessage());
        
        return dto;
    }

    @Override
    public List<Comment> toEntity(List<CommentDto> dtoList) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public List<CommentDto> toDto(List<Comment> entityList) {
        List<CommentDto> dtoList = new ArrayList<>();
        for (Comment instance : entityList) {
            dtoList.add(toDto(instance));
        }
        return dtoList;
    }
    
    private String getUserName(String userId) {
        if (StringUtils.isEmpty(userId)) {
            return null;
        }
        User user = identityService.createUserQuery().userId(userId).singleResult();
        if (user != null) {
            return user.getFirstName();
        }
        return null;
    }
}
